<template>
  <view class="container">
    <!-- 头部 -->
    <view class="header">
      <u-icon name="arrow-left" size="40" color="#333" @click="goBack" class="back-button"></u-icon>
      <text class="title">体检订单</text>
    </view>

    <!-- 订单详情 -->
    <view class="order-details">
      <view class="detail-item">
        <text class="label">套餐名称：</text>
        <text class="value">{{ packageDetail.packageName || '普通入职体检' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">医院名称：</text>
        <text class="value">{{ hospitalName || '北京市第二医院体检中心' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">预约时间：</text>
        <text class="value">{{ getAppointmentTime }}</text>
      </view>
      <view class="detail-item">
        <text class="label">有效期：</text>
        <text class="value">{{ validityEndDate }}</text>
      </view>
      <view class="detail-item">
        <text class="label">就诊人：</text>
        <picker @change="bindPatientPickerChange" :value="patientIndex" :range="patientOptions" range-key="name">
          <view class="value">{{ selectedPatient ? selectedPatient.name : '请选择就诊人' }}</view>
        </picker>
      </view>
      <view class="detail-item">
        <text class="label">支付方式：</text>
        <text class="value">支付宝</text>
      </view>
      <view class="detail-item">
        <text class="label">价格：</text>
        <text class="value">¥{{ packageDetail.price || '286' }}</text>
      </view>
    </view>

    <!-- 底部提交栏 -->
    <view class="fixed-bottom">
      <button class="submit-btn" @click="showConfirm">提交订单</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      hospitalId: null,
      hospitalName: null,
      packageDetail: {
        packageName: null,
        price: null,
        validityPeriod: null,
        id: null
      },
      selectedPeriod: null,
      date: null,
      patientIndex: 0,
      patientOptions: [], // 就诊人列表，存储 { id, name } 对象
      selectedPatient: null,
      validityEndDate: null
    };
  },
  onLoad(options) {
    let userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.id) {
      this.userId = userInfo.id;
    } else {
      console.warn('未找到用户ID，跳转到登录页面');
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/public/login' });
          }, 2000);
        }
      });
    }

    this.hospitalId = options.hospitalId;
    this.packageDetail.id = options.packageId;
    // 修改1：优化 period 的接收，确保直接使用传入的 AM 或 PM 字符串
    // 原因：前端已经保证 period 是大写的 AM 或 PM，无需额外转换
    this.selectedPeriod = options.period; // 直接接收 AM 或 PM
    this.date = options.date;
    // 查询医院和套餐详情
    this.fetchHospitalDetail();
    this.fetchPackageDetail();
    this.fetchPatientList();
    this.calculateValidityEndDate();
  },
  computed: {
    // 计算预约时间显示
    getAppointmentTime() {
      if (!this.date || !this.selectedPeriod) return '请选择预约时间';
      const periodText = this.selectedPeriod === 'AM' ? '上午 (08:00-12:00)' : '下午 (13:00-17:00)';
      return `${this.date} ${periodText}`;
    }
  },
  methods: {
    // 返回
    goBack() {
      uni.navigateBack();
    },
    // 查询医院详情
    fetchHospitalDetail() {
      uni.request({
        url: `http://localhost:8080/app/hospital/detail/${this.hospitalId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            this.hospitalName = res.data.data.name;
          } else {
            uni.showToast({
              title: res.data.msg || '查询医院详情失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    // 查询套餐详情
    fetchPackageDetail() {
      uni.request({
        url: `http://localhost:8080/app/physical/order/detail/${this.packageDetail.id}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            this.packageDetail = { ...this.packageDetail, ...res.data.data };
            this.calculateValidityEndDate();
          } else {
            uni.showToast({
              title: res.data.msg || '查询套餐详情失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    // 查询就诊人列表
    fetchPatientList() {
      uni.request({
        url: 'http://localhost:8080/app/hospital/patient/list', // 假设后端接口
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            // 解析后端返回的 rows 数组
            this.patientOptions = res.data.rows.map(item => ({
              id: item.id,
              name: item.name
            }));
            if (this.patientOptions.length > 0) {
              this.selectedPatient = this.patientOptions[0]; // 默认选择第一个就诊人
            }
          } else {
            uni.showToast({
              title: res.data.msg || '查询就诊人失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    // 计算有效期结束日期
    calculateValidityEndDate() {
      if (this.packageDetail.validityPeriod) {
        const today = new Date();
        const endDate = new Date(today);
        endDate.setDate(today.getDate() + this.packageDetail.validityPeriod);
        const year = endDate.getFullYear();
        const month = String(endDate.getMonth() + 1).padStart(2, '0');
        const day = String(endDate.getDate()).padStart(2, '0');
        this.validityEndDate = `${year}-${month}-${day}`;
      }
    },
    // 选择就诊人
    bindPatientPickerChange(e) {
      this.patientIndex = e.detail.value;
      this.selectedPatient = this.patientOptions[this.patientIndex];
    },
    // 显示支付确认框
    showConfirm() {
      // 验证必填字段
      if (!this.selectedPatient) {
        uni.showToast({
          title: '请选择就诊人',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '确认支付',
        content: `您将支付 ¥${this.packageDetail.price}，是否确认？`,
        success: (res) => {
          if (res.confirm) {
            this.submitOrder();
          } else if (res.cancel) {
            console.log('用户取消支付');
          }
        }
      });
    },
    // 提交订单并处理支付
    submitOrder() {
      console.log('开始提交订单:' + this.userId);
      const orderData = {
        userId: this.userId,
        packageId: this.packageDetail.id.toString(),
        hospitalId: this.hospitalId.toString(),
        patientId: this.selectedPatient.id.toString(),
        packagePrice: this.packageDetail.price.toString(),
        date: this.date,
        // 修改2：优化 period 的传递，确保直接使用 AM 或 PM 字符串
        // 原因：前端已经保证 period 是大写的 AM 或 PM，无需额外转换
        period: this.selectedPeriod // 直接传递 AM 或 PM
      };

      uni.request({
        url: 'http://localhost:8080/app/physical/pay',
        method: 'POST',
        data: orderData,
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          console.log('支付请求成功，返回数据:', res);
          if (res.statusCode === 200 && res.data) {
            // 解析并提交支付宝表单
            this.handlePayForm(res.data);
          } else {
            uni.showToast({
              title: '支付请求失败，状态码: ' + res.statusCode,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.log('支付请求失败:', err);
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none',
            duration: 2000
          });
        },
        complete: () => {
          console.log('支付请求完成');
        }
      });
    },
    // 处理支付宝支付表单并跳转
    handlePayForm(formData) {
      // 动态创建一个临时的 div 元素来解析表单
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = formData;

      // 获取表单元素
      const form = tempDiv.querySelector('form');
      if (form) {
        // 将表单添加到页面
        document.body.appendChild(form);
        // 手动提交表单，跳转到支付宝支付页面
        form.submit();
      } else {
        uni.showToast({
          title: '支付表单解析失败',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
};
</script>

<style>
.container {
  padding-bottom: 100rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.back-button {
  margin-right: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.order-details {
  padding: 30rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.label {
  color: #666;
  font-size: 28rpx;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: white;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.submit-btn {
  background: #007AFF;
  color: white;
  font-size: 32rpx;
  padding: 0 60rpx;
  border-radius: 50rpx;
  line-height: 2.2;
}
</style>